package com.zsr.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ContextServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //ServletContext类的作用
        //        1.获取web.xml中配置的上下文参数context-param
        ServletContext context=getServletConfig().getServletContext();
        String username=context.getInitParameter("username");
        System.out.println("context-param的参数是："+username);

        //        2.获取当前的工程路径，格式：/工程路径
        System.out.println("当前工程路径："+context.getContextPath());

        //        3.获取工程部署后在服务器硬盘上的绝对路径
        /**
         *   / 斜杠被服务器解析地址为：http://ip:port/工程名/ <br/>
         *
         * */
        System.out.println("工程部署的路径："+context.getRealPath("/"));
        System.out.println("工程下的css文件路径："+context.getRealPath("/css"));

        //        4.像Map一样存取数据
        ServletContext context1= getServletContext();

        System.out.println("保存之前：Context中获取域数据："+context1.getAttribute("key1"));

        context1.setAttribute("key1","value1");
        System.out.println("Context中获取域数据："+context1.getAttribute("key1"));
    }
}
